package cn.tedu.rpc;

import com.rabbitmq.client.*;
import com.rabbitmq.client.AMQP.BasicProperties;
import java.io.IOException;

public class Server {
    public static void main(String[] args) throws Exception{
        //1.配置RabbitMQ的连接信息
        ConnectionFactory cf = new ConnectionFactory();
        cf.setHost("127.0.0.1");
        cf.setUsername("guest");
        cf.setPassword("guest");
        //2.创建tcp和channel
        Connection nc = cf.newConnection();
        Channel cc = nc.createChannel();
        //3.创建调用队列
        cc.queueDeclare("rpc_queue",false,false,false,null);
        //4.从调用队列中获取调用信息进行处理
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                //从delivery对象中取出n
                String str = new String(delivery.getBody());
                int n = Integer.parseInt(str);
                //获取返回队列名
                String replyTo = delivery.getProperties().getReplyTo();
                //获取关联id
                String cid = delivery.getProperties().getCorrelationId();
                Long fbnqs = fbnqs(n);
                //向返回队列发送计算结果，需要携带关联id
                BasicProperties basicProperties =
                        new BasicProperties().builder().correlationId(cid).build();
                cc.basicPublish("",replyTo,basicProperties,(fbnqs+"").getBytes());
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {

            }
        };
        cc.basicConsume("rpc_queue",true,deliverCallback,cancelCallback);
    }
    public static Long fbnqs(int n){
        if(n==1 || n==2)
            return 1L;
        return fbnqs(n-1)+fbnqs(n-2);
    }
}
